import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import Polygon from "ol/geom/Polygon";
import Point from "ol/geom/Point";
import { Fill, Stroke, Circle, Style } from "ol/style";
import Draw from "ol/interaction/Draw";
import Extent from "ol/interaction/Extent";
import DragBox from "ol/interaction/DragBox";
import { click, shiftKeyOnly } from "ol/events/condition";
import { createXYZ } from "ol/tilegrid";
import { fromLonLat } from "ol/proj";
import { tile as tileStrategy } from "ol/loadingstrategy";
import EsriJSON from "ol/format/EsriJSON";
import { transformExtent, toLonLat } from "ol/proj";
import TileLayer from "ol/layer/Tile";
import TileArcGISRest from "ol/source/TileArcGISRest";
export class map {
  map: any = "";
  Interaction: any;
}
export const operation = {
  map: new map().map,
  polylineToArray(polyline: string) {
    const arr = polyline.split("|");
    let a2 = [];
    for (let item of arr) {
      let a1 = [];
      for (let val of item.split(";")) {
        const a = val.split(",");
        a1.push([+a[0], +a[1]]);
      }
      a2.push(a1);
    }
    return a2;
  },
  getLayerById(map: any, id: string) {
    return map
      .getLayers()
      .getArray()
      .find((item: any) => item.values_.id == id);
  },
  addGraphicsToLayer(map: any, options: { clearBefore: any; geometrys: any; layerId: any; style?: any }) {
    const features: any = [];
    options.geometrys.forEach((element: any) => {
      features.push(
        new Feature({
          geometry: element,
        })
      );
    });

    let layer = this.getLayerById(map, options.layerId);
    console.log(layer);
    if (layer) {
      if (options.clearBefore) layer.getSource().clear();
      layer.getSource().addFeatures(features);
    } else {
      const layer = new VectorLayer({
        id: options.layerId,

        source: new VectorSource({
          features: features,
        }),
      });
      if (options.style) layer.setStyle(options.style);
      map.addLayer(layer);
    }
  },
  createSymbol(fillColor: any, width: number, borderColor: any, borderType?: string) {
    return new Style({
      fill: new Fill({ color: fillColor }),
      stroke: new Stroke({ color: borderColor, width }),
    });
  },
  /**
   * @geometryType The geometry type. One of 'Point', 'LineString', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection', 'Circle'.
   *
   *  */
  getInteractionById(id: string, map?: any) {
    map = map || this.map;
    return map
      .getInteractions()
      .getArray()
      .find((item: any) => item.values_.id == id);
  },
  drawGraphic(option: { geometryType: string; map?: any }) {
    var targetMap = option.map || this.map,
      drawInteraction = this.getInteractionById("draw", targetMap);

    if (!drawInteraction) {
      drawInteraction = new Draw({
        type: option.geometryType,
      });
      targetMap.addInteraction(drawInteraction);
    }
    targetMap.addInteraction(drawInteraction);
    drawInteraction.setActive(true);
    drawInteraction.setProperties({
      type: option.geometryType,
    });
    return new Promise((resolve) => {
      drawInteraction.on("drawend", (evt: any) => {
        drawInteraction.setActive(false);
        console.log(evt);
        // console.log(evt);
        resolve(evt.feature.getGeometry());
      });
    });
  },
  addEsri() {
    const t = new TileLayer({
      map: operation.map,
      source: new TileArcGISRest({
        url: "http://192.168.0.201:6080/arcgis/rest/services/vsgs/xsq/MapServer",
      }),
    });
    console.log(t);
    operation.map.on("click", (evt: any) => {
      const [x, y] = toLonLat(operation.map.getCoordinateFromPixel(evt.pixel), "EPSG:3857");
      var url =
        "http://192.168.0.201:6080/arcgis/rest/services/vsgs/xsq/FeatureServer/3" +
        "/query/?f=json&" +
        "returnGeometry=true&spatialRel=esriSpatialRelIntersects" +
        "&geometry=" +
        encodeURI('{"x":' + x + ',"y":' + y + ',"spatialReference":{"wkid":4326}}') +
        "&geometryType=esriGeometryPoint&inSR=102100&outFields=*" +
        "&outSR=102100";
      fetch(url)
        .then((evt) => evt.json())
        .then((response) => {
          var esrijsonFormat = new EsriJSON();
          var features = esrijsonFormat.readFeatures(response, {
            featureProjection: "EPSG:3857",
          });
          if (features.length > 0)
            features.forEach((feature: any) => {
              operation.addGraphicsToLayer(operation.map, {
                clearBefore: true,
                geometrys: [feature.getGeometry()],
                layerId: "selectLayer",
              });
            });
        });
    });
  },
  addEsri_() {
    var esrijsonFormat = new EsriJSON();
    var vectorSource = new VectorSource({
      loader: function(extent: any, resolution: any, projection: any) {
        extent = transformExtent(extent, "EPSG:3857", "EPSG:4326");
        var url =
          "http://192.168.0.201:6080/arcgis/rest/services/vsgs/xsq/FeatureServer/3" +
          "/query/?f=json&" +
          "returnGeometry=true&spatialRel=esriSpatialRelIntersects" +
          "&geometry=" +
          encodeURIComponent(
            '{"xmin":' +
              extent[0] +
              ',"ymin":' +
              extent[1] +
              ',"xmax":' +
              extent[2] +
              ',"ymax":' +
              extent[3] +
              ',"spatialReference":{"wkid":4326}}'
          ) +
          "&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*" +
          "&outSR=102100";
        fetch(url, {
          method: "get",
        })
          .then((res) => {
            return res.json();
          })
          .then((response) => {
            console.log(response);
            if (response.error) {
              alert(response.error.message + "\n" + response.error.details.join("\n"));
            } else {
              // dataProjection will be read from document
              var features = esrijsonFormat.readFeatures(response, {
                featureProjection: projection,
              });
              console.log(features);
              // features = features.slice(0, 1000);
              if (features.length > 0) {
                vectorSource.addFeatures(features);
              }
            }
          });
      },
      strategy: tileStrategy(
        createXYZ({
          tileSize: 512,
        })
      ),
    });

    var layer = operation.getLayerById(operation.map, "drawLayer");
    if (layer) {
      layer.setSource(vectorSource);
      return;
    }

    var vector = new VectorLayer({
      id: "drawLayer",
      source: vectorSource,
    });
    operation.map.addLayer(vector);
  },
};
